package com.funny.stock.base.service;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;


public abstract class BaseCrudService<T,ID> implements CrudService<T,ID> , InitializingBean {

    JpaRepository<T,ID> baseRepository;

    protected abstract JpaRepository<T,ID> setupJpaRepository();

    @Override
    public <S extends T> S save(S entity) {
        return baseRepository.save(entity);
    }

    @Override
    public <S extends T> Iterable<S> saveAll(Iterable<S> entities) {
        return baseRepository.saveAll(entities);
    }

    @Override
    public Optional<T> findById(ID id) {
        return baseRepository.findById(id);
    }

    public T queryById(ID id) {
        return baseRepository.findById(id).orElse(null);
    }

    @Override
    public boolean existsById(ID id) {
        return baseRepository.existsById(id);
    }

    @Override
    public Iterable<T> findAll() {
        return baseRepository.findAll();
    }

    @Override
    public Iterable<T> findAllById(Iterable<ID> ids) {
        return baseRepository.findAllById(ids);
    }

    @Override
    public long count() {
        return baseRepository.count();
    }

    @Override
    public void deleteById(ID id) {
        baseRepository.deleteById(id);
    }

    @Override
    public void delete(T entity) {
        baseRepository.delete(entity);
    }

    @Override
    public void deleteAll(Iterable<? extends T> entities) {
        baseRepository.deleteAll(entities);
    }

    @Override
    public void deleteAll() {
        baseRepository.deleteAll();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
//        System.out.println(getClass().getSimpleName());
        baseRepository = setupJpaRepository();

    }
}
